﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
namespace Baby.GrowUp.Data
{


    /// <summary>
    /// 数据对象扩展类
    /// </summary>
    public static class DataObjectExtend
    {


        /// <summary>
        /// 将当前DataTable封装为指定类型的对象
        /// </summary>
        /// <typeparam name="T">需要将DataTable转换到的目标对象</typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T[] ToObject<T>(this DataTable obj) where T:class
        {

            Type type = typeof(T);
            

            List<T> objList = new List<T>();

            #region 将DataTable封装为对象
            foreach (DataRow row in obj.Rows)
            {

                T rowObj = row.ToObject<T>();
                objList.Add(rowObj);
            }
            #endregion


            return objList.ToArray();
        
        }
        
        /// <summary>
        /// 将当前DataRow封装为指定类型的对象
        /// </summary>
        /// <typeparam name="T">需要将DataTable转换到的目标对象</typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T ToObject<T>(this DataRow obj) where T : class
        {
            DataColumnCollection columns = obj.Table.Columns;
            ObjectProxy<T> proObj = new ObjectProxy<T>();
            string[] fields = proObj.Fields;


            foreach (string f in fields)
            {
                if (columns.Contains(f))
                {
                    object fieldValue = obj[f];
                    proObj.SetField(f, fieldValue);
                }
            }

            return proObj.TargetObject;
            


        }

        public static T FillObject<T>(this DataRow thisObj, T tarObj) where T:class
        {
            DataColumnCollection columns = thisObj.Table.Columns;
            ObjectProxy<T> proObj = new ObjectProxy<T>(tarObj);
            string[] fields = proObj.Fields;


            foreach (string f in fields)
            {
                if (columns.Contains(f))
                {
                    object fieldValue = thisObj[f];
                    proObj.SetField(f, fieldValue);
                }
            }

            return proObj.TargetObject;

           
        }

    }
}
